<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能问答系统</title>
    <style>
        /* 全局样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        /* 页面容器 */
        .container {
            width: 100%;
            max-width: 800px;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            background-color: #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        /* 标题 */
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
            padding: 20px 0;
            background-color: #fafafa;
            border-bottom: 1px solid #ddd;
        }

        /* 问答区域 */
        .chat-container {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #fafafa;
        }

        /* 用户输入区域 */
        .input-container {
            padding: 20px;
            background-color: #fff;
            border-top: 1px solid #ddd;
            display: flex;
            gap: 10px;
        }

        .input-container input {
            flex: 1;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 4px;
            outline: none;
        }

        .input-container button {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .input-container button:hover {
            background-color: #0056b3;
        }

        /* 消息气泡 */
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
            max-width: 70%;
        }

        .message.user {
            background-color: #007bff;
            color: #fff;
            margin-left: auto;
        }

        .message.bot {
            background-color: #f1f1f1;
            color: #333;
            margin-right: auto;
        }

        /* 加载动画 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }
    </style>
    <!-- Markdown 解析库 -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <!-- 代码高亮库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
</head>
<body>
<div class="container">
    <h1>智能问答系统</h1>
    <div class="chat-container" id="chat-container">
        <!-- 聊天记录将显示在这里 -->
    </div>
    <div class="input-container">
        <input type="text" id="question-input" placeholder="请输入您的问题...">
<!--        <textarea id="question-input" placeholder="请输入您的问题..."></textarea>-->
        <button id="submit-btn">发送</button>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const questionInput = document.getElementById('question-input');
        const submitBtn = document.getElementById('submit-btn');
        const chatContainer = document.getElementById('chat-container');
        const container = document.querySelector('.container');

        // 提交问题的函数
        submitBtn.addEventListener('click', handleSubmit);

        // 为输入框添加回车键监听器
        questionInput.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                event.preventDefault(); // 阻止默认行为（比如表单提交）
                handleSubmit(); // 调用提交处理函数
            }
        });

        async function handleSubmit() {
            const question = questionInput.value.trim();
            if (!question) {
                alert('请输入问题！');
                return;
            }

            // 清空输入框
            questionInput.value = '';

            // 添加用户消息
            addMessage('user', question);

            // 添加加载动画
            const loadingMessage = addMessage('bot', '<div class="loading"></div>');

            // 调整布局，使输入框沉底
            container.style.justifyContent = 'flex-start';

            try {
                // 模拟流式响应
                const response = await fetch('http://localhost:8080/api/v1/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: question,
                });

                if (!response.ok) {
                    throw new Error(`请求失败，状态码：${response.status}`);
                }

                // 使用 ReadableStream 处理流式响应
                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let botResponse = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) {
                        console.log('流式响应结束');
                        break;
                    }

                    // 解码流数据
                    const chunk = decoder.decode(value, { stream: true });
                    console.log('接收到数据块:', chunk);

                    // 解析数据块并显示内容
                    const lines = chunk.split('\n');
                    for (const line of lines) {
                        if (line.startsWith('data:')) {
                            const jsonData = line.substring(5).trim();
                            if (jsonData === '[DONE]') {
                                console.log('流式响应完成');
                                break;
                            }

                            try {
                                const data = JSON.parse(jsonData);
                                const content = data.choices[0].delta.content || '';
                                botResponse += content;

                                // 将 Markdown 转换为 HTML
                                const htmlContent = marked.parse(botResponse);

                                // 更新机器人消息
                                loadingMessage.innerHTML = htmlContent;

                                // 高亮代码块
                                hljs.highlightAll();
                            } catch (error) {
                                console.error('解析 JSON 数据失败:', error);
                            }
                        }
                    }
                }
                if (botResponse === '') {
                    loadingMessage.innerHTML = '抱歉，我暂时无法回答您的问题。';
                }
            } catch (error) {
                console.error('请求出错:', error);
                loadingMessage.innerHTML = '请求出错，请重试。';
            }
        }

        // 添加消息到聊天容器
        function addMessage(role, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role}`;
            messageDiv.innerHTML = content;
            chatContainer.appendChild(messageDiv);

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;

            return messageDiv;
        }
    });
</script>
</body>
</html>